/**
 * 
 */
package org.rhq.plugins.tools.httpcheck;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
import org.rhq.core.pluginapi.inventory.ResourceComponent;
import org.rhq.core.pluginapi.inventory.ResourceContext;

/**
 * @author lgao
 *
 */
public class HttpPathResourceComponent implements ResourceComponent, HttpCheckerConstants{

	private static final Logger LOG = Logger.getLogger(HttpPathResourceComponent.class);
	
	private ResourceContext context;
	
	/*
	 * TODO
	 * 1. implement ConfigurationFacet
	 * 2. implement MeasurementFacet
	 * 3. implement AlertFacet
	 * 4. using Event ??
	 */
	
	public AvailabilityType getAvailability() {
		Configuration config = context.getPluginConfiguration();
		String path = config.getSimpleValue(PLUGIN_CONFIG_PATH_KEY, "/");
		
		HttpHostResourceComponent hostComp = (HttpHostResourceComponent)context.getParentResourceComponent();
		
		// load plugin configuration
		String host = hostComp.loadPluginConfiguration().getSimpleValue(PLUGIN_CONFIG_HOST_KEY, "");
		String port = hostComp.loadPluginConfiguration().getSimpleValue(PLUGIN_CONFIG_PORT_KEY, "80");
			HttpURLConnection conn = null;
			try {
				StringBuilder sb = new StringBuilder("http://" + host + ":" + port);
				if(path.startsWith("/")){
					sb.append(path);
				}else{
					sb.append("/" + path);
				}
				URL url = new URL(sb.toString());
				conn = (HttpURLConnection)url.openConnection();
				conn.setConnectTimeout(5000);
				conn.connect();
				int code = conn.getResponseCode();
				if(code == 200){ // only 200 means OK
					return AvailabilityType.UP;
				}else{
					hostComp.sendNotification(path);
					return AvailabilityType.DOWN;
				}
			} catch (MalformedURLException e) {
				throw new IllegalArgumentException(e);
			} catch (IOException e) {
				LOG.warn(e);
				hostComp.sendNotification(path);
				return AvailabilityType.DOWN;
			}finally{
				if(null != conn){
					conn.disconnect();
				}
			}
	}

	public void start(ResourceContext _context)
			throws InvalidPluginConfigurationException, Exception {
		this.context = _context;
	}

	public void stop() {
		this.context = null;
	}

}
